/**
 * 
 */
package neptune.web.client.controller;

import java.util.Arrays;

import neptune.web.client.WebInterface;
import neptune.web.client.commands.OpenExperimentViewCommand;
import neptune.web.client.view.ConsoleManager;
import neptune.web.client.view.ExperimentView;
import neptune.web.client.view.OperativeView;
import neptune.web.client.view.SuperView;
import neptune.web.client.view.ViewManager;
import neptune.web.client.view.components.LongMessageWidget;
import neptune.web.client.view.components.MessageWidget;
import neptune.web.client.view.components.TopologyPanel;

import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;

public class DescriptorUploadController implements FormHandler {
	/**
	 * 
	 */
	private final TopologyPanel topologyPanel;

	public static class UploadErrorCodes {
		public static final int OK = 0;
		public static final int EXCEPTION = 1;
		public static final int SECURITY_EXCEPTION = 2;
	}

	/**
	 * @param topologyPanel
	 */
	public DescriptorUploadController(TopologyPanel topologyPanel) {
		this.topologyPanel = topologyPanel;
	}

	private PopupPanel loadingPopup;
	public static final String SEPARATOR_CHAR = "-R-s-t-S-e-p-";

	private void showLoadingDialog(Widget message) {
		loadingPopup = new DialogBox(false, true);
		loadingPopup.add(message);
		loadingPopup.setAnimationEnabled(true);
		loadingPopup.setStylePrimaryName("TopologyPanelDialog");
		loadingPopup.center();
	}

	private void hideLoadingDialog() {
		if (loadingPopup != null)
			loadingPopup.hide();
	}

	public void onSubmitComplete(FormSubmitCompleteEvent event) {
		hideLoadingDialog();
		String message = "";

		if (event.getResults() == null) {
			message = "Unable to verify upload correctness.";
			WebInterface.showMessageDialog(new MessageWidget(
					MessageWidget.ERROR, message), true);
			return;
		}

		String[] resultTexts = event.getResults().split(SEPARATOR_CHAR, 4);
		System.out.println(Arrays.toString(resultTexts));
		int result = Integer.parseInt(resultTexts[0]);

		if (result == UploadErrorCodes.OK) {

			String experimentStatus = resultTexts[1];
			String topologyStatus = resultTexts[2];
			String validationLog = resultTexts[3];
			message = "Topology upload completed. \n"
					+ "WARNING: Only if the validation process gives a VALID result "
					+ "the topology file is actually saved on the server."
					+ "\n\n\n" + "Topology validation result: "
					+ topologyStatus;
			ConsoleManager.addConsoleMessage(message, false);
			WebInterface.showMessageDialog(new LongMessageWidget(
					MessageWidget.MESSAGE, message + "\nValidation log:\n"
							+ validationLog), true);

			// Imposta lo stato dell'esperimento
			SuperView operative = (SuperView) ViewManager.getViewManager()
					.getViewByName(OperativeView.DEFAULT_TOKEN);

			ExperimentView expView = (ExperimentView) operative
					.getViewByName(ExperimentView.DEFAULT_TOKEN);

			expView.setExperimentState(experimentStatus);

		} else {
			message = "Upload topology file error: " + resultTexts[1];
			ConsoleManager.addConsoleMessage(message, true);
			WebInterface.showMessageDialog(new MessageWidget(
					MessageWidget.ERROR, message), true);
		}

		// Information update
		(new OpenExperimentViewCommand(this.topologyPanel.getExpName()))
				.execute();
	}

	public void onSubmit(FormSubmitEvent event) {
		this.topologyPanel.getUpLoadFilePanel().removeStyleDependentName(
				"invalidEntry");
		String message;
		// Verifica che sia selezionato un file
		if (this.topologyPanel.getFileUploadInput().getFilename().equals("")) {
			message = "Select a topology file to upload.";
			this.topologyPanel.getUpLoadFilePanel().addStyleDependentName(
					"invalidEntry");
			WebInterface.showMessageDialog(new MessageWidget(
					MessageWidget.ERROR, message), true);
			ConsoleManager.addConsoleMessage(message, true);
			event.setCancelled(true);
			return;
		}

		message = "Loading topology file...";
		ConsoleManager.addConsoleMessage(message, false);
		showLoadingDialog(new MessageWidget(MessageWidget.LOADING, message));
		// TODO inserire la logica della richiesta
	}
}